#include "StdAfx.h"
#include "TinyModule.h"
#include "ModuleDefine.h"


CTinyModule::CTinyModule(void)
: m_config(NULL)
, m_bExit(false)
, m_pThread(NULL)
{
}

CTinyModule::~CTinyModule(void)
{
}
bool CTinyModule::start(void)
{
	if(m_config == NULL)
		return false;

	m_pThread = new TinyCC::CTinyThread( this, &CTinyModule::reciveMsgFunc,  (void*)this );
	//_beginthreadex( NULL, 0, &CTinyModule::reciveMsgFunc,  (void*)this, 0, &threadID);
	return false;
}

bool CTinyModule::end(void)
{
	m_bExit = true;
	//wait for receiveMsg thread end
	return false;
}
void CTinyModule::reciveMsgFunc( void* param)
{
	//CTinyModule * me = (CTinyModule*)param;

	m_bExit = false;

	HANDLE TCPEvent=CreateEvent(NULL,true,false,NULL);
	m_TCPServer.init();
	m_TCPServer.startRecv(m_config->m_ModuleIP.c_str() ,m_config->m_ModulePort,TCPEvent);
	//Sleep( 10000 );

	int iLoopCount = 0;
	TinyCC::msg::CTinyTCPMsg tinyTCPMsg;
	TinyCC::msg::CTinyMsg tinyMsg,outputMsg;
	SOCKET socketID = 0;
	long length=0;
	const char * data = NULL;

	//msg Process
	while(true)
	{
		if( m_bExit )
		{
			break;
		}
		switch( WaitForSingleObject( TCPEvent,10 ) )
		{
			case WAIT_OBJECT_0:
				{
					ResetEvent( TCPEvent );
					iLoopCount++;

					tinyMsg.clear();
					int maxNumber = 100;
					while( m_TCPServer.getNextMsg(&tinyMsg,socketID)&& maxNumber > 0 )
					{
						outputMsg.setMsgIndex(0);
						outputMsg.setMsgIndex(0);
						outputMsg.setSocketID(socketID);
						ProcessReceivedMsg(tinyMsg,outputMsg);
						//send reply msg then
						if(outputMsg.getMsgIndex()!=0||outputMsg.getMsgItem()!=0)
						{
							data =tinyTCPMsg.package(length,&outputMsg);
							m_TCPServer.sendData(socketID,(void*)data,length);
							outputMsg.clear();
						}
						tinyMsg.clear();
						maxNumber--;
					}//while

					/*curtime = time(NULL);
					if( curtime - lasttime >= 1 )
					{
						iLoopCount = 0;
						//g_Timer.springTimer();
						lasttime = time(NULL);
						curtime = time(NULL);
					}*/
					
				}
				break;
			default:
				{

					/*iLoopCount++;
					if( iLoopCount >= 20 || curtime - lasttime >= 1 )
					{
						iLoopCount = 0;
						g_Timer.springTimer();

						lasttime = time(NULL);
						curtime = time(NULL);
					}*/
				}
				break;
		}//switch
	}//while

	return  ;
}
